#include "worker.h"
#include "config.h"

namespace qtch {

static qtch::ConfigVar<std::map<std::string, std::map<std::string,std::string> > >::ptr g_worker_conf
    = qtch::Config::LookUp("worker", std::map<std::string,std::map<std::string,std::string> >(), "worker config");

WorkerManager::WorkerManager()
    :m_stop(false) {
}

void WorkerManager::add(Scheduler::ptr s) {
    if(!s){
        return;
    }
    if(m_datas.size()==0 && m_stop == true){
        m_stop = false;
    }
    m_datas[s->getName()] = s;
}

Scheduler::ptr WorkerManager::get(const std::string& name) {
    auto it = m_datas.find(name);
    if(it == m_datas.end()){
        return nullptr;
    }
    return it->second;
}

IOManager::ptr WorkerManager::getAsIOManager(const std::string& name) {
    return std::dynamic_pointer_cast<IOManager>(get(name));
}

bool WorkerManager::init() {
    auto workers = g_worker_conf->getValue();
    return init(workers);
}

bool WorkerManager::init(const std::map<std::string,std::map<std::string,std::string> >& v) {
    for(auto& i : v){
        std::string name = i.first;
        int32_t thread_num = qtch::GetParamValue(i.second,"thread_num",1);
        Scheduler::ptr s = std::make_shared<IOManager>(thread_num,false,name);
        s->start();
        add(s);
    }
    m_stop = m_datas.empty();
    return true;

}

void WorkerManager::stop() {
    if(m_stop){
        return;
    }
    for(auto& i : m_datas){
        IOManager::ptr iom = std::dynamic_pointer_cast<IOManager>(i.second);
        if(iom){
            iom->delAllTimer();
        }
        i.second->stop();
    }
    m_datas.clear();
    m_stop = true;
}

std::ostream& WorkerManager::dump(std::ostream& os) {
    os << "WorkerManager:{\n";
    for(auto& i : m_datas){
        i.second->dump(os);
        os << "\n";
    }
    os << "}";
    return os;
}

std::string WorkerManager::toString(){
    std::stringstream ss;
    dump(ss);
    return ss.str();
}

uint32_t WorkerManager::getCount() {
    return m_datas.size();
}


}